package com.camera.yl.fragment

import android.annotation.SuppressLint
import android.util.Log
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.PopupWindow
import android.widget.TextView
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.Observer
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.android.arouter.launcher.ARouter
import com.camera.base.Log.YLogImpl
import com.camera.base.v.BaseFragment
import com.camera.device.dao.ActualFileDaoHelper
import com.camera.routemodule.RouterPath
import com.camera.yl.R
import com.camera.yl.databinding.FragmentFileBinding
import com.camera.yl.databinding.ItemFileDirectoryBinding
import com.camera.yl.manager.UploadManager
import com.camera.yl.models.UploadInfo
import com.camera.yl.v.models.FileViewModel
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.emptyFlow
import kotlinx.coroutines.launch
import java.io.File

@AndroidEntryPoint
class FileFragment : BaseFragment<FragmentFileBinding>() {
    companion object{
        val TAG = FileFragment::class.java.simpleName
    }
    var type:Int = -1
    private val viewModel: FileViewModel by activityViewModels()
    private var uploadPopupWindow: PopupWindow? = null

    override fun loadData(isRefresh: Boolean) {
        viewModel.showGallery.observe(this, Observer {
            if (type == 1) {
                val a =  it.paths as List<File>?
                ARouter.getInstance().build(RouterPath.path.gallery_activity).withString("path", a?.get(it.position)!!.absolutePath).withTransition(R.anim.slide_in_right, R.anim.slide_out_left).navigation()
            }
        })
        
        // 观察上传弹窗显示状态
        viewModel.showUploadPanel.observe(this, Observer { show ->
            if (show) {
                showUploadPopup()
            } else {
                hideUploadPopup()
            }
        })
        
        val fileAdapter = mBinding.rvFragmentFiles.adapter as FileAdapter
        lifecycleScope.launch {
            when (type) {
                1 -> viewModel.fileAudioList
                0 -> viewModel.fileVideoList
                else -> emptyFlow()
            }.collectLatest { files ->
                files?.let { fileAdapter.setItems(it) }
            }
        }
        
        // 观察选择模式状态变化，更新适配器
        lifecycleScope.launch {
            viewModel.isSelectionMode.collectLatest { isSelectionMode ->
                fileAdapter.updateSelectionMode(isSelectionMode)
                // 选择模式下给RecyclerView添加底部padding，避免被弹窗挡住
                updateRecyclerViewPadding(isSelectionMode)
            }
        }
        
        // 观察选中文件变化，更新适配器
        lifecycleScope.launch {
            viewModel.selectedFiles.collectLatest { selectedFiles ->
                fileAdapter.updateSelectedFiles(selectedFiles)
                updateUploadPopupCount(selectedFiles.size)
            }
        }
        
        // 观察上传文件事件
        viewModel.uploadFilesEvent.observe(this, Observer { filePaths ->
            filePaths?.let {
                // 启动上传服务
                UploadManager.startUpload(requireContext(), it)
            }
        })
        
        // 观察上传状态变化
        UploadManager.uploadStatusLiveData.observe(this, Observer { uploadStatusMap ->
            // 通知适配器更新上传状态
            fileAdapter.updateUploadStatus(uploadStatusMap)
        })
        
        lifecycleScope.launch {
            viewModel.loadDirectories(type)
        }

    }
    
    override fun initView() {
        type = requireArguments().getInt("type")
        mBinding.viewModel = viewModel
        
        // 设置当前tab类型到ViewModel
        viewModel.setCurrentTab(type)
        
        val mLinearLayoutManager = LinearLayoutManager(mContext)
        mBinding.rvFragmentFiles!!.layoutManager = mLinearLayoutManager
        mBinding.rvFragmentFiles.adapter = FileAdapter(
            onClick = { file, type, position ->
                viewModel.onItemClicked(file, type, position)
            },
            onLongClick = { file, type ->
                viewModel.onItemLongClicked(file, type)
            },
            onCheckboxClick = { file ->
                viewModel.toggleFileSelection(file)
            }
        )
    }

    override fun getLayoutId(): Int {
        return R.layout.fragment_file
    }
    
    /**
     * 显示上传弹窗
     */
    private fun showUploadPopup() {
        if (uploadPopupWindow?.isShowing == true) return
        
        val popupView = LayoutInflater.from(mContext).inflate(R.layout.popup_upload, null)
        uploadPopupWindow = PopupWindow(
            popupView,
            ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.WRAP_CONTENT,
            false  // 设置为false，外部点击不消失
        )
        
        val btnUpload = popupView.findViewById<Button>(R.id.btn_upload)
        btnUpload.setOnClickListener {
            viewModel.uploadSelectedFiles()
        }
        
        // 设置弹窗动画和显示
        uploadPopupWindow?.animationStyle = R.style.PopupAnimation
        uploadPopupWindow?.isOutsideTouchable = false  // 外部点击不消失
        uploadPopupWindow?.isFocusable = false  // 不获取焦点，避免影响其他交互
        uploadPopupWindow?.showAtLocation(mBinding.root, Gravity.BOTTOM, 0, 0)
        
        // 初始化选中文件数量显示
        updateUploadPopupCount(viewModel.getSelectedCount())
    }
    
    /**
     * 隐藏上传弹窗
     */
    private fun hideUploadPopup() {
        uploadPopupWindow?.dismiss()
        uploadPopupWindow = null
    }
    
    /**
     * 更新上传弹窗中的选中文件数量
     */
    private fun updateUploadPopupCount(count: Int) {
        uploadPopupWindow?.contentView?.findViewById<TextView>(R.id.tv_selected_count)?.text = 
            "已选择 $count 个文件"
    }
    
    /**
     * 根据选择模式更新RecyclerView的底部padding
     */
    private fun updateRecyclerViewPadding(isSelectionMode: Boolean) {
        val bottomPadding = if (isSelectionMode) {
            // 选择模式下添加底部padding，避免被弹窗挡住，大约80dp的高度
            (80 * resources.displayMetrics.density).toInt()
        } else {
            // 正常模式保持原有padding
            resources.getDimensionPixelSize(com.camera.base.R.dimen.qb_px_20)
        }
        
        mBinding.rvFragmentFiles.setPadding(
            resources.getDimensionPixelSize(com.camera.base.R.dimen.qb_px_20), // left
            resources.getDimensionPixelSize(com.camera.base.R.dimen.qb_px_20), // top
            resources.getDimensionPixelSize(com.camera.base.R.dimen.qb_px_20), // right
            bottomPadding // bottom
        )

    }

    inner class FileAdapter(
        private val onClick: (File, Int, Int) -> Unit,
        private val onLongClick: (File, Int) -> Boolean,
        private val onCheckboxClick: (File) -> Unit
    ) : RecyclerView.Adapter<FileAdapter.FileViewHolder>() {

        private val items = mutableListOf<File>()
        private var isSelectionMode = false
        private var selectedFiles: Set<File> = emptySet()
        private var uploadStatusMap: Map<String, UploadInfo> = emptyMap()

        @SuppressLint("NotifyDataSetChanged")
        fun setItems(newItems: List<File>) {
            items.clear()
            items.addAll(newItems)
            notifyDataSetChanged()
        }
        
        fun updateSelectionMode(selectionMode: Boolean) {
            if (isSelectionMode != selectionMode) {
                isSelectionMode = selectionMode
                notifyDataSetChanged()
            }
        }
        
        fun updateSelectedFiles(selected: Set<File>) {
            if (selectedFiles != selected) {
                selectedFiles = selected
                notifyDataSetChanged()
            }
        }
        
        /**
         * 更新上传状态映射
         */
        fun updateUploadStatus(statusMap: Map<String, UploadInfo>) {
            if (uploadStatusMap != statusMap) {
                val oldMap = uploadStatusMap
                uploadStatusMap = statusMap
                
                // 检查是否有文件从状态映射中移除（说明上传完成）
                val removedFiles = oldMap.keys - statusMap.keys
                if (removedFiles.isNotEmpty()) {
                    // 有文件上传完成，需要重新绑定这些文件项以显示已上传标志
                    YLogImpl.d("FileAdapter", "检测到${removedFiles.size}个文件上传完成，将刷新UI")
                    notifyDataSetChanged()
                } else {
                    // 只是状态更新，正常刷新
                    notifyDataSetChanged()
                }
            }
        }

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): FileViewHolder {
            val inflater = LayoutInflater.from(parent.context)
            val binding = DataBindingUtil.inflate<ItemFileDirectoryBinding>(
                inflater, R.layout.item_file_directory, parent, false
            )
            return FileViewHolder(binding)
        }

        override fun onBindViewHolder(holder: FileViewHolder, position: Int) {
            val item = items[position]
            holder.bind(item, position)
        }

        override fun getItemCount(): Int = items.size

        inner class FileViewHolder(private val binding: ItemFileDirectoryBinding) :
            RecyclerView.ViewHolder(binding.root) {
            fun bind(file: File, position: Int) {
                binding.item = file
                binding.isSelectionMode = isSelectionMode
                binding.isSelected = selectedFiles.contains(file)
                
                // 先设置默认状态（不显示进度条）
                binding.uploadStatus = null
                binding.uploadProgress = 0
                
                if (file.isDirectory) {
                    binding.drawable = R.drawable.directory
                } else {
                    binding.drawable = R.drawable.mp4
                }
                
                binding.clickListener = View.OnClickListener { 
                    onClick(file, type, position) 
                }
                
                binding.longClickListener = View.OnLongClickListener { 
                    onLongClick(file, type)
                }
                
                binding.checkboxClickListener = View.OnClickListener {
                    onCheckboxClick(file)
                }
                
                // 设置上传状态图标和进度条
                if (!file.isDirectory) {
                    // 需要根据数据库查询实际的upload状态
                    lifecycleScope.launch {
                        val actualFile = ActualFileDaoHelper.getByPath(file.absolutePath)
                        if (actualFile != null) {
                            // 设置已上传图标
                            binding.ivHttpUploadStatus.visibility = if (actualFile.upload == 0) View.VISIBLE else View.GONE
                            binding.ivFtpUploadStatus.visibility = if (actualFile.upload_ftp == 0) View.VISIBLE else View.GONE
                            
                            // 只有当文件未上传时，才显示进度条
                            if (actualFile.upload != 0) {
                                val uploadInfo = uploadStatusMap[file.absolutePath]
                                if (uploadInfo != null) {
                                    binding.uploadStatus = uploadInfo.status
                                    binding.uploadProgress = uploadInfo.progress
                                }
                            }
                        } else {
                            binding.ivHttpUploadStatus.visibility = View.GONE
                            binding.ivFtpUploadStatus.visibility = View.GONE
                            
                            // 如果数据库中没有记录，也检查是否有上传状态
                            val uploadInfo = uploadStatusMap[file.absolutePath]
                            if (uploadInfo != null) {
                                binding.uploadStatus = uploadInfo.status
                                binding.uploadProgress = uploadInfo.progress
                            }
                        }
                    }
                } else {
                    binding.ivHttpUploadStatus.visibility = View.GONE
                    binding.ivFtpUploadStatus.visibility = View.GONE
                }
                
                binding.executePendingBindings()
            }
        }
    }

    override fun onBack():Boolean{
        return viewModel.onBack(type)
    }
    
    override fun onDestroy() {
        super.onDestroy()
        hideUploadPopup()
    }
}